﻿using System;
using System.Configuration;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace FKMC.Core.Configuration
{
    public class NhibernateConfigurations
    {
        public ISessionFactory CreateSessionFactory(bool isDbReCreated = false)
        {
            if (!isDbReCreated)
                return Fluently.Configure()
                               .Database(MsSqlConfiguration.MsSql2012
                                   .Raw("connection.isolation", "ReadCommitted")
                                   .ConnectionString(ConfigurationManager.ConnectionStrings[Environment.MachineName.ToUpper()]
                                           .ConnectionString))
                               .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("FKMC.Domain")))
                               .ExposeConfiguration(c => c.SetInterceptor(new EntityTimeStampInterceptor()))
                               .BuildSessionFactory();

            return Fluently.Configure()
                           .Database(
                               MsSqlConfiguration.MsSql2012.Raw("connection.isolation", "ReadCommitted").ConnectionString(
                                   ConfigurationManager.ConnectionStrings[Environment.MachineName.ToUpper()]
                                       .ConnectionString))
                           .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("FKMC.Domain")))
                           .ExposeConfiguration(c => c.SetInterceptor(new EntityTimeStampInterceptor()))
                           .ExposeConfiguration(BuildSchema)

                           .BuildSessionFactory();

        }

        private void BuildSchema(NHibernate.Cfg.Configuration config)
        {
            new SchemaUpdate(config).Execute(false, true);
            new SchemaExport(config).Drop(false, true);
            new SchemaExport(config).Create(false, true);
        } 
    }
}